package cn.com.css.taxInspection.common.sysjob.task;

import cn.com.css.taxInspection.common.sysjob.service.ZhBusinessService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.ReentrantLock;


/**
 * 关注查补
 */
@Component("ZhTask")
public class ZhTask {

    private static final Logger logger = LoggerFactory.getLogger(ZhTask.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    private final ZhBusinessService zhBusinessService;

    private final ReentrantLock lock = new ReentrantLock();

    public ZhTask(ZhBusinessService zhBusinessService) {
        this.zhBusinessService = zhBusinessService;
    }

    public void run() {
        if (!lock.tryLock()) {
            logger.warn("综合口定时任务正在执行中，本次跳过。");
            return;
        }

        try {
            logger.info("综合定时任务执行，当前时间 :{}", dateFormat.format(new Date()));
            int maxRetry = 3;
            int attempt = 0;
            boolean success = false;

            while (attempt < maxRetry && !success) {
                try {
                    attempt++;
                    zhBusinessService.checkSystemStatus();
                    success = true;
                    logger.info("系统状态检查成功，尝试次数: {}", attempt);
                } catch (Exception e) {
                    logger.warn("第 {} 次执行关注查补任务失败: {}", attempt, dateFormat.format(new Date()));
                    logger.error("系统状态检查异常:", e);
                    if (attempt >= maxRetry) {
                        logger.error("已达到最大重试次数({})，仍然失败，可以在此处添加报警逻辑", maxRetry);
                    } else {
                        try {
                            Thread.sleep(2000); // 等待 2 秒
                        } catch (InterruptedException ie) {
                            Thread.currentThread().interrupt();
                            logger.warn("重试等待被中断");
                        }
                    }
                }
            }
        } finally {
            lock.unlock(); // 别忘了解锁！
        }
    }
}
